package com.chen.sample2.web.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.chen.sample2.common.message.ResponseMsg;
import com.chen.sample2.web.service.ICacheService;
import com.chen.sample2.web.service.ITestService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Date;

/**
 * @desc
 * @Author Chentian
 */
@Service
public class TestServiceImpl implements ITestService {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    public static final String DEFAULT_WORD = "world";

    @Autowired
    private ICacheService cacheService;

    @Autowired
    private CacheManager cacheManager;

    @Override
    public ResponseMsg hello() {
        ResponseMsg responseMsg = new ResponseMsg();

        String message = "hello word! time:"+ DateUtil.formatDateTime(new Date());
        responseMsg.setData(message);

        String cacheKey = "hello";
        cacheService.put(cacheKey, JSONUtil.toJsonStr(responseMsg));

        ResponseMsg res = cacheService.get(cacheKey,ResponseMsg.class);
        logger.info(JSONUtil.toJsonStr(res));
        return res;
    }

    /**
     * 使用 Caffeine 本地缓存 cacheManager
     */
    @Cacheable(value = "word", key = "#word")
    @Override
    public ResponseMsg word(String word) {
        logger.info("word:{}",word);
        String msg = "hello "+ word+", time:"+ DateUtil.formatDateTime(new Date());
        if(DEFAULT_WORD.equals(word)){
            msg = "[Super] hello world! time:"+ DateUtil.formatDateTime(new Date());
        }
        return ResponseMsg.createSuccessResponse(msg);
    }

    /**
     * 使用 Caffeine 手动填充
     */
    @Override
    public ResponseMsg localCache() {
        String cacheName = "name";
        Cache nameCache = cacheManager.getCache(cacheName);
        nameCache.put("chen","yes");

        Collection<String> cacheNames = cacheManager.getCacheNames();
        return ResponseMsg.createSuccessResponse(JSONUtil.toJsonStr(cacheNames));
    }

}
